# Create your views here.
import logging
from django.db.models import Q
from rest_framework import status
from rest_framework.response import Response
from book1.models import Word, ImageData, Describe, Explain
from book1.serializers import WordSerializer, ImageDataSerializer, DescribeSerializer, ExplainSerializer, ParentSerializer
from fdfs_client.client import get_tracker_conf, Fdfs_client
from utils.myModelViewSet import IsAuthenticatedViewSet
from variant_character.models import SimilarCharacter

tracker_path = get_tracker_conf('utils/fastdfs/client.conf')
client = Fdfs_client(tracker_path)
logger = logging.getLogger(__name__)



class WordViewSet(IsAuthenticatedViewSet):
    queryset = Word.objects.all()
    serializer_class = WordSerializer

    def create(self, request, *args, **kwargs):
        try:
            word_explain = request.data['word_explain']
        except:
            return Response({"msg": "关键字段缺失1"})
        explain_serializer = ExplainSerializer(data=word_explain)
        explain_serializer.is_valid(raise_exception=True)
        explain_serializer.save()
        explain_id = explain_serializer.data['id']
        try:
            otherInfo = request.data['otherInfo']
        except:
            return Response({"msg": "关键字段缺失2"})
        desc_serializer = DescribeSerializer(data=otherInfo)
        desc_serializer.is_valid(raise_exception=True)
        desc_serializer.save()
        otherInfo_id = desc_serializer.data['id']
        try:
            word = request.data["word"]
        except:
            return Response({"msg": "请输入词条名称"})
        try:
            label = request.data["file_label"]
        except:
            return Response({"msg": "请输入那一本书名、对应的版本和第几卷"})
        try:
            Similar_character = request.data['Similar_character']
        except:
            return Response({"msg": "请输入异体字字段"})
        word_explain = Explain.objects.filter(id=explain_id)
        otherInfo = Describe.objects.filter(id=otherInfo_id)
        request_data = {
            "word": word,
            "file_label": label,
            "Similar_character": Similar_character,
        }
        serializer = self.get_serializer(data=request_data)
        serializer.is_valid(raise_exception=True)
        Word.objects.create(word=word, file_label=label, word_explain=word_explain[0], otherInfo=otherInfo[0],
                            Similar_character=Similar_character)
        return Response({"msg": "数据已上传"})

    def update(self, request, *args, **kwargs):
        """
        修改 异体字 字段
        """
        try:
            word = Word.objects.get(id=kwargs['pk'])
        except Word.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        try:
            Similar_character_id = list(set(request.data['Similar_character'].split(';')))
        except:
            return Response({'msg': "请输入Similar_character字段"})
        if len(Similar_character_id) == 1:
            try:
                SimilarCharacter.objects.get(id=Similar_character_id[0].split("_")[0])
            except SimilarCharacter.DoesNotExist:
                return Response({"msg": "上传的异体字id无效"})
        else:
            for i in Similar_character_id:
                parent_id, id_ = tuple(i.split("_"))
                try:
                    SimilarCharacter.objects.get(id=id_)
                except SimilarCharacter.DoesNotExist:
                    return Response({"msg": "上传的异体字id无效"})
        Similar_character_id = [i for i in Similar_character_id if not i in word.Similar_character]
        word.Similar_character = word.Similar_character + ";" + ";".join(Similar_character_id)
        word.save()
        serializer = self.get_serializer(word)
        return Response(serializer.data)

    def advanced_search(self, request, pk):
        # 词条 释义 加 书名
        try:
            word = Word.objects.filter(Q(word__contains=pk) | Q(file_label__contains=pk) | Q(word_explain__word__contains=pk))
        except Word.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(word, many=True)
        return Response(serializer.data)

    def common_search(self, request, pk):
        # 单个 词条查询
        word = Word.objects.filter(word__contains=pk)
        if not word:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(word, many=True)
        return Response(serializer.data)


class ImageViewSet(IsAuthenticatedViewSet):
    queryset = ImageData.objects.all()
    serializer_class = ParentSerializer

    # permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        # 确定类型  1:上传book 2:上传某本书的版本 3:上传某一版本的 图片
        request_data = dict()
        try:
            type_ = request.data['type']
        except:
            return Response({'msg': "type为必填字段", 'tips': "{1:上传book 2:上传某本书的版本 3:上传某一版本的 图片}"})
        if isinstance(type_, int):
            type_ = str(type_)
        if type_.isdigit():
            if eval(type_) in (1, 2, 3):
                if type_ == '1':
                    name = request.data.get('name', "没有")
                    if name == "没有":
                        return Response({'msg': "name为必填字段"})
                    request_data['name'] = name
                elif type_ == '2':
                    name = request.data.get('name', "没有")
                    if name == "没有":
                        return Response({'msg': "name为必填字段"})
                    request_data['name'] = name
                    parent = request.data.get('parent', "没有")
                    if parent == "没有":
                        return Response({'msg': "parent为必填字段"})
                    request_data['parent'] = parent
                else:
                    try:
                        parent = request.data['parent']
                        request_data['parent'] = parent
                    except:
                        return Response({'msg': "parent为必填字段"})
                    try:
                        files = request.FILES.get('file')
                    except:
                        return Response({'msg': "请上传文件"})
                    # 上传到FastDFS文件系统中
                    try:
                        files_name = files.name.split('.')[0]
                    except Exception as e:
                        return Response({"msg": "请输入文件名"})
                    request_data['name'] = files_name
                    image_ext_name = 'png'
                    try:
                        upload_res = client.upload_by_buffer(files.read(), file_ext_name=image_ext_name)
                    except Exception as e:
                        logger.error('图片上传出现错误：{}'.format(e))
                        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                    else:
                        if upload_res.get('Status') != 'Upload successed.':
                            return Response({'msg': '图片上传失败，请稍后重试或联系管理员'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                        else:
                            image_url = upload_res.get('Remote file_id').decode()
                            request_data['save_id'] = image_url
                serializer = ImageDataSerializer(data=request_data)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                return Response(serializer.data)
            else:
                return Response({"msg": "type is out of range"})
        else:
            return Response({'msg': "type类型必须为数字"})

    def get_bookName(self, request):
        book = ImageData.objects.filter(parent_id=None)
        serializer = ImageDataSerializer(book, many=True)
        return Response(serializer.data)
